package markan.fb;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import markan.PostSubmit;

public class TCFacebookHelper {
	
	//APP 정보
	private final static String APP_ID = "339258482837278";
	private final static String APP_SECRET = "d9d2ae415ae8a473823701f6655b6c53";
	private final static String REDIRECT_URI = "http://localhost:8080/facebookAccessToken.jsp?id=";
	private final static String PERMISSION_NAMES = "manage_pages,publish_stream,user_groups,offline_access";
	
	/**
	 * 페이스북 로그인 URL을 생성한다.
	 * @param redirectUri
	 * @return
	 */
	public static String getOuathUrl(String redirectUri) {
		String facebookOuathUrl = "";
		try {
			facebookOuathUrl = "https://www.facebook.com/dialog/oauth?"
						+ "client_id=" + APP_ID
						+ "&redirect_uri=" + URLEncoder.encode(redirectUri, "UTF-8")
						+ "&scope=" + PERMISSION_NAMES;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return facebookOuathUrl;
	}
	
	/**
	 * 페이스북 로그인 URL을 생성한다.
	 * @param facebookId
	 * @return
	 */
	public static String getOuathUrl(int facebookId) {
		String facebookOuathUrl = "";
		try {
			facebookOuathUrl = "https://www.facebook.com/dialog/oauth?"
						+ "client_id=" + APP_ID
						+ "&redirect_uri=" + URLEncoder.encode(REDIRECT_URI + facebookId, "UTF-8")
						+ "&scope=" + PERMISSION_NAMES;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return facebookOuathUrl;
	}
	
	/**
	 * 토큰을 가져온다.
	 * @param code
	 * @param facebookId
	 * @return
	 */
	public static Map<String, String> getAccessToken(String code, int facebookId) {
		
		String tokenUrl = "";
		try {
			tokenUrl = "https://graph.facebook.com/oauth/access_token?"
				       		+ "client_id=" + APP_ID 
				       		+ "&redirect_uri=" + URLEncoder.encode(REDIRECT_URI + facebookId, "UTF-8")
				       		+ "&client_secret=" + APP_SECRET 
				       		+ "&code=" + code
							+ "&locale=ko_KR";
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		
		String accessToken = "";
		String expires = "";
		
		HttpURLConnection conn = null;
		InputStream is = null;
		BufferedReader br = null;
		
		StringBuffer response = new StringBuffer();
		try {
			URL url = new URL(tokenUrl);
			
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setConnectTimeout(2000);
			conn.setReadTimeout(12000);
			conn.setInstanceFollowRedirects(false);
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlendcoded");
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.connect();
	
			is = conn.getInputStream();		
			br = new BufferedReader(new InputStreamReader(is));
			String line;
			while ((line = br.readLine()) != null) {
				response.append(line);
			}
			
			String json = response.toString();
			String[] arr = json.split("&");
			for (int i = 0; i < arr.length; i++) {
				String[] temp = arr[i].split("=");
				if (temp[0].equals("access_token")) {
					accessToken = temp[1];
					
				}
				if (temp[0].equals("expires")) {
					expires = temp[1];
				}
			}			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(br!=null) try { br.close(); }catch(Exception e) { }
			if(is!=null) try { is.close(); }catch(Exception e) { }
			if(is!=null) try { is.close(); }catch(Exception e) { }
			if(conn!=null) try { conn.disconnect(); }catch(Exception e) { }
		}
		
		Map<String, String> result = new HashMap<String, String>();
		result.put("accessToken", accessToken);
		result.put("expires", expires);
		
		return result;
	}
	
	public static void publishLikes(String  objectId, String access_token) {
		String sendUrl = "https://graph.facebook.com/" + objectId + "/likes";
		String message = "access_token=" + access_token;
		
		PostSubmit send = new PostSubmit();
		send.sendData(sendUrl, message);
		
		//https://graph.facebook.com/313449204401/likes?access_token=
	}
}
